﻿package net.wangit.support.action;

import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextImpl;
import net.wangit.context.LocalContext;
import net.wangit.framework.action.OutActionResult;
import net.wangit.framework.config.GlobalSettings;
import net.wangit.framework.util.ResponseWriter;
import net.wangit.support.Action;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 处理下载时，必须指定此类或子类。
 * 
 * @author watson Feb 25, 2010
 */
public abstract class DownloadAction implements Action {

	private static final Log log = LogFactory
			.getLog(net.wangit.support.action.DownloadAction.class);

	public DownloadAction() {
	}

	// 处理下载。
	public ActionContext execute(ActionContext ac) throws Exception {
		LocalContext lc = LocalContext.getLocalContext();
		HttpServletResponse response = lc.getHttpServletResponse();
		try {
			doDownload(ac, response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ResponseWriter.write(response, "无法下载：未知的异常，请联系管理员.");
		}
		((ActionContextImpl) ac).setActionResult(new OutActionResult());
		return ac;
	}

	protected OutputStream getOutputStream(HttpServletResponse response,
			String fileName, String contentType) throws Exception {
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		response.setHeader("Content-disposition", (new StringBuilder(
				"attachment;filename=")).append(fileName).toString());
		response
				.setContentType((new StringBuilder(String.valueOf(contentType)))
						.append(";charset=").append(
								GlobalSettings.getEncoding()).toString());
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		return response.getOutputStream();
	}

	// 下载接口。
	protected abstract void doDownload(ActionContext actioncontext,
			HttpServletResponse httpservletresponse) throws Exception;

}
